//
//  HealthNewsListViewController.m
//  LoveHealth
//
//  Created by 枫哥 on 14-9-18.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "HealthNewsListViewController.h"


#import "HealthNewsCell.h"
#import "ScrollViewCell.h"
#import "HealthNewsDetailViewController.h"
//图片下载第三方头文件
#import "UIImageView+WebCache.h"
#import "UIImage+Adittion.h"
//loading第三方头文件
#import "MONActivityIndicatorView.h"
//搜索功能使用的头文件
#import "SearchViewController.h"
//下拉刷新、上拉显示更多第三方头文件
#import "MJRefresh.h"
//封装的网络判断头文件
#import "NetHelper.h"
//网络判断弹出提示使用的第三方头文件
#import "KGStatusBar.h"

@interface HealthNewsListViewController ()<MONActivityIndicatorViewDelegate>

//声明一个loading用于加载未完成时
@property (nonatomic,retain)MONActivityIndicatorView  * indicatorView;
//声明一个可变数组newsArray用于存储获取的资讯类型
@property (nonatomic,retain)NSMutableArray * newsArray;
//声明一个可变数组allNewsArray用于显示在cell上的的资讯
@property (nonatomic,retain)NSMutableArray * allNewsArray;
//声明一个tableView显示资讯列表
@property (nonatomic,retain)UITableView * listTableView;
//声明一个imageView显示滚动轮播图
@property (nonatomic,retain)UIImageView * newsImageView;
//声明一个请求网络时page参数  page默认是1
@property (nonatomic,assign)NSInteger page;
//发起网络请求用于tableView
- (void)p_sendReuqestTableView:(NSNumber *)classNumber page:(NSInteger)page;

//导航栏设置
- (void)p_setupNavigationBarItem;
@end

@implementation HealthNewsListViewController
- (void)dealloc
{
    
    Block_release(_pushDVCBlock);
    self.indicatorView = nil;
    self.allNewsArray = nil;
    self.listTableView = nil;
    self.newsArray = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    //默认page为第一页
    self.page = 1;
    self.navigationItem.title = @"资讯列表";
    //设置背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    
        
    //初始化tableView
    CGRect frame = self.view.frame;
    _listTableView = [[UITableView alloc]initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height -49-84-16) style:UITableViewStyleGrouped];
    _listTableView.backgroundView = nil;
    NSLog(@"frame = %@",[NSValue valueWithCGRect:_listTableView.frame]);
    [self.view addSubview:_listTableView];
    
    
    //自定义视图中tableView的代理设置
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    
    
    //初始化allNewsArray存放tableView上的数据
    self.allNewsArray = [NSMutableArray array];
    
    //设置加载loading
    [self setupActivityIndicator];

    //设置导航栏
    [self p_setupNavigationBarItem];
    
    //网络请求获取数据（两个参数 第一个是咨询分类的ID 第二个是请求页数  默认是一页：20条数据）
    [self p_sendReuqestTableView:self.newsClass.ID page:1];
    //刷新
    [self setupRefresh];
    
    
  
}


//下拉刷新，上拉显示更多
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_listTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_listTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.listTableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.listTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.listTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    self.listTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.listTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.listTableView.footerRefreshingText = @"正在帮你加载中,不客气";
}

- (void)headerRereshing
{
    
    [self p_sendReuqestTableView:self.newsClass.ID page:1];
    [self.listTableView reloadData];
    [self.listTableView headerEndRefreshing];
}

- (void)footerRereshing
{
    
    self.page++;
    [self p_sendReuqestTableView:self.newsClass.ID page:self.page];
    
    [self.listTableView reloadData];
    [self.listTableView footerEndRefreshing];
}


#pragma mark-----------------loading------------
//设置loading
- (void)setupActivityIndicator
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.delegate = self; //设置代理
    _indicatorView.numberOfCircles = 6; //圆圈个数
    _indicatorView.radius = 10;//圆圈大小
    _indicatorView.internalSpacing = 3;//圆圈之间的间距
    _indicatorView.center = self.view.center;
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}
//指示器 代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    CGFloat alpha = 1.0f;
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

#pragma mark------------------导航栏---------------
//导航栏设置
- (void)p_setupNavigationBarItem
{
    UIBarButtonItem * rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrowDown"] style:UIBarButtonItemStyleDone target:self action:@selector(didClickRightBarButtonAction:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    [rightBarButtonItem release];
 
}


#pragma mark-------------------发起网络请求获取资讯列表-------
//网络请求用于显示在cell上的数据
- (void)p_sendReuqestTableView:(NSNumber *)classNumber page:(NSInteger)page
{
    NSArray * imgArray = [NSArray arrayWithObjects:@"img/news/20140806092251_722.png",@"img/news/20140620111812_51.png",@"img/news/20140516094150_533.jpg",@"img/news/20140520094041_602.jpg",@"img/news/20140518104511_88.jpg", nil];
    //网络请求的拼接字符串
    NSString * str = [NSString stringWithFormat:@"%@?id=%@&page=%ld",APIHealthNewsList,classNumber,self.page];
    
    //开始loading
    [self.indicatorView startAnimating];
    
    __block HealthNewsListViewController * newsListVC = self;
    //使用封装的网络判断
    [[NetHelper shareInstance]loadingDataWithUrlString:str urlExpireInSeconds:30 download:^(NSURLResponse *response, NSData *data, NSError *error) {
        //如果数据不为空并且没有错误时
        if (data != nil && error == nil) {
            NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //必须要加判断 如果不加 下拉刷新的时候又请求第一页的20条数据 加到了allNewsArray中 造成数据错乱
            if (page == 1) {
                [_allNewsArray removeAllObjects];
            }
            //数据处理
            NSArray * sourceArray = sourceDic[@"yi18"];
            
            for (NSDictionary * dic in sourceArray) {
                HealthNews * news = [[HealthNews alloc] init];
                
                news.img = imgArray[arc4random()%5];
                [news setValuesForKeysWithDictionary:dic];
                [newsListVC.allNewsArray addObject:news];
                [news release];
            }
            
        }else {
            //显示网络判断提示
            [KGStatusBar showErrorWithStatus:kNetErrorMessage];
        }

        //刷新数据
        [newsListVC.listTableView reloadData];
        //停止loading
        [newsListVC.indicatorView stopAnimating];
    }];
 
  /*  [NetHelper loadingDataWithUrlString:str download:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        
        
        
        NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        if (page == 1) {
            [_allNewsArray removeAllObjects];
        }
        //数据处理
        NSArray * sourceArray = sourceDic[@"yi18"];
        for (NSDictionary * dic in sourceArray) {
            HealthNews * news = [[HealthNews alloc] init];
            
            news.img = imgArray[arc4random()%5];
            [news setValuesForKeysWithDictionary:dic];
            [newsListVC.allNewsArray addObject:news];
            [news release];
            
            
        }
        
        //刷新数据
        [newsListVC.listTableView reloadData];
        [newsListVC.indicatorView stopAnimating];

    }];*/
    
//    
//    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        //解析数据
//        
//        NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        
//        if (nil == self.allNewsArray) {
//            self.allNewsArray = [NSMutableArray array];
//        }
//        //数据处理
//        NSArray * sourceArray = sourceDic[@"yi18"];
//        for (NSDictionary * dic in sourceArray) {
//            HealthNews * news = [[HealthNews alloc] init];
//
//             news.img = imgArray[arc4random()%5];
//            [news setValuesForKeysWithDictionary:dic];
//            [newsListVC.allNewsArray addObject:news];
//            [news release];
//
//
//        }
//        
//        
//        //刷新数据
//        [newsListVC.listTableView reloadData];
//        [newsListVC.indicatorView stopAnimating];
//        
//    }];
    
}

#pragma mark -------------------UITableViewDateSource数据源----------
//设置分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

//设置每个分区的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //当第一分区时，轮播图
    if (section == 0) {
        return 1;
    }
    //第二分区时（显示列表）
    return [self.allNewsArray count];
}
//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //轮播图高度140
    if (indexPath.section == 0) {
        return 140;
    }
    //显示列表高度100
    return 100;
}
//设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //第一分区显示轮播图
    if (indexPath.section == 0) {
        static NSString * identifierSVC = @"identifierSVC";
        ScrollViewCell * SVcell = [tableView dequeueReusableCellWithIdentifier:identifierSVC];
        if (nil == SVcell) {
            SVcell  = [[[ScrollViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierSVC] autorelease];
        }
        //初始化数组newsArray存放后3条数据显示在轮播图上
        NSMutableArray * newsArray = [NSMutableArray arrayWithCapacity:10];
        //必须要加判断 等数据回来的时候（第一次执行时allNewsArray为空 请求网络数据还没回来）
        if (_allNewsArray.count > 18) {
            SVcell.firstImageView.userInteractionEnabled = YES;
            for (int i = 14; i >= 12; i --) {
                HealthNews * healthnews = _allNewsArray[i];
                [newsArray addObject:healthnews];
            }
            //实现block  推出详情页面
            SVcell.pushDetailViewBock = ^(HealthNews * news){
                
                //推出详情block（在HostViewController中）
                self.pushDVCBlock(news);
                
            };
            //自定义cell方法  传回一个数组（轮播图数据）
            [SVcell setImageWithArray:newsArray];
            
        }
        return SVcell;
    }
    
    static NSString * identifier = @"cell";
    HealthNewsCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (nil == cell) {
        cell = [[[HealthNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
    }
    
    HealthNews * aNews = _allNewsArray[indexPath.row];
    cell.news = aNews;
    
    
    return cell;
}
//设置分区头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

//选中cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HealthNews * sNews = _allNewsArray[indexPath.row];
    HealthNewsCell * customcell = (HealthNewsCell *)[tableView cellForRowAtIndexPath:indexPath];
    sNews.showImage = customcell.newsImageView.image;
    
    self.pushDVCBlock(sNews);
}
////选中轮播图
//- (void)didClickImage
//{
//    HealthNewsDetailViewController * newsDetailVC = [[HealthNewsDetailViewController alloc] init];
//    ScrollViewCell * cell = (ScrollViewCell *)[_listTableView viewWithTag:19];
//    HealthNews * news = _allNewsArray[19];
//    NSString * url = APIImageURL(news.img);
//    NSLog(@"url = %@",url);
//    //     [cell.firstImageView setImageWithURL:[NSURL URLWithString:url]];
//    newsDetailVC.news = news;
//    news.showImage = cell.firstImageView.image;
//    NSLog(@"mage = %@",cell.firstImageView.image);
//    [self.navigationController pushViewController:newsDetailVC animated:YES];
//    [newsDetailVC release];
//    //    NSLog(@"count = %ld",[_imageArray count]);
//    //    NSInteger i;
//    //    HealthNews * sNews = _allNewsArray[i];
//    
//    
//}

#pragma mark -----------------------点击导航栏事件------------------------
- (void)didClickRightBarButtonAction:(UIBarButtonItem *)barButtonItem
{
    
}












- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
